<template>
  <div class="chapter-editor">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <n-spin size="large" />
      <p class="loading-text">正在加载章节数据...</p>
    </div>
    
    <!-- 编辑器内容 -->
    <div v-show="!loading" class="editor-container">
      <div class="editor-content">
        <!-- 根据当前活动标签页显示对应内容 -->
        <div v-if="activeTab === 'content'" class="editor-pane">
          <div v-if="!isPreviewMode" class="editor-input-container">
            <n-input
              v-model:value="chapterContent"
              type="textarea"
              placeholder="请输入章节正文内容..."
              class="content-editor custom-scrollbar"
              ref="contentEditorRef"
              :disabled="contentLoading"
            />
            <!-- 正文加载遮罩动画 -->
            <div v-if="contentLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成章节正文" />
            </div>
          </div>
          <div v-else class="preview-pane custom-scrollbar" ref="contentPreviewRef">
            <MarkdownRenderer :content="chapterContent" />
            <!-- 正文加载遮罩动画 -->
            <div v-if="contentLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成章节正文" />
            </div>
          </div>
        </div>
        
        <div v-if="activeTab === 'outline'" class="editor-pane">
          <div v-if="!isPreviewMode" class="editor-input-container">
            <n-input
              v-model:value="chapterOutline"
              type="textarea"
              placeholder="请输入章节细纲，描述本章节的主要情节、人物行为和场景..."
              class="content-editor custom-scrollbar"
              ref="outlineEditorRef"
              :disabled="outlineLoading"
            />
            <!-- 细纲加载遮罩动画 -->
            <div v-if="outlineLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成章节细纲" />
            </div>
          </div>
          <div v-else class="preview-pane custom-scrollbar" ref="outlinePreviewRef">
            <MarkdownRenderer :content="chapterOutline" />
            <!-- 细纲加载遮罩动画 -->
            <div v-if="outlineLoading" class="loading-overlay-container">
              <LoadingDots :visible="true" message="正在生成章节细纲" />
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部标签页和按钮组 -->
    <div class="editor-tabs">
      <n-tabs v-model:value="activeTab" type="line" animated :tab-style="{ minWidth: '80px', maxWidth: '120px', height: '32px' }">
        <n-tab-pane name="content" tab="章节正文">
        </n-tab-pane>
        <n-tab-pane name="outline" tab="章节细纲">
        </n-tab-pane>
        <template #suffix>
          <n-space :size="4">
            <n-button @click="togglePreviewMode" :type="isPreviewMode ? 'primary' : 'default'" size="small">
              {{ isPreviewMode ? '编辑' : '预览' }}
            </n-button>
            <n-button @click="copyContent(activeTab)" size="small">
              复制
            </n-button>
            <n-button @click="clearContent(activeTab)" size="small">
              清空
            </n-button>
            <n-button v-if="activeTab === 'content'" @click="showGenerateContentDialog" type="primary" size="small" :disabled="!chapterOutline.trim()">
              生成正文
            </n-button>
            <n-button v-if="activeTab === 'outline'" @click="showGenerateOutlineDialog" type="primary" size="small">
              生成细纲
            </n-button>
            <n-button @click="resetChapter" :disabled="loading" size="small" type="error">
              <template #icon>
                <n-icon><RefreshIcon /></n-icon>
              </template>
              重置
            </n-button>
            <n-button type="primary" @click="saveChapter" :loading="saving" size="small">
              保存
            </n-button>
          </n-space>
        </template>
      </n-tabs>
    </div>
    
    <!-- 生成对话框 -->
    <GenerateDialog
      v-model:visible="generateDialogVisible"
      :title="generateDialogTitle"
      :confirm-button-text="generateDialogConfirmText"
      :loading="generateDialogLoading"
      :form="generateDialogForm"
      :template-category="generateDialogTemplateCategory"
      :modal-class="generateDialogModalClass"
      @model-select="handleGenerateModelSelect"
      @template-select="handleGenerateTemplateSelect"
      @confirm="handleGenerateConfirm"
      @cancel="handleGenerateCancel"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage, useDialog } from 'naive-ui'
import { Refresh as RefreshIcon } from '@vicons/tabler'
import { chapterContentApi } from '../services/chapter-content-service'
import { useCurrentBookStore } from '../stores/current-book'
import MarkdownRenderer from '../../shared/components/MarkdownRenderer.vue'
import LoadingDots from '../../shared/components/LoadingDots.vue'
import GenerateDialog from '../components/GenerateDialog.vue'


const route = useRoute()
const router = useRouter()
const message = useMessage()
const dialog = useDialog()
const currentBookStore = useCurrentBookStore()

// 响应式数据
const loading = ref(false)
const chapterContent = ref('')
const chapterOutline = ref('')
const isPreviewMode = ref(true)
const saving = ref(false)
const activeTab = ref('content')
const selectedChapter = ref(null)

// 加载动画控制
const contentLoading = ref(false)
const outlineLoading = ref(false)

// 引用DOM元素
const contentEditorRef = ref(null)
const contentPreviewRef = ref(null)
const outlineEditorRef = ref(null)
const outlinePreviewRef = ref(null)
const contentTextareaRef = ref(null)
const outlineTextareaRef = ref(null)

// 生成对话框相关
const generateDialogVisible = ref(false)
const generateDialogTitle = ref('')
const generateDialogConfirmText = ref('开始生成')
const generateDialogLoading = ref(false)
const generateDialogForm = ref({
  modelId: null,
  systemPromptId: null,
  appendMode: 'overwrite'
})
const generateDialogTemplateCategory = ref('')
const generateDialogModalClass = ref('')
const currentGenerateType = ref('')

// 元素引用配置
const elementRefs = {
  content: {
    editorRef: contentEditorRef,
    previewRef: contentPreviewRef,
    textareaRef: contentTextareaRef
  },
  outline: {
    editorRef: outlineEditorRef,
    previewRef: outlinePreviewRef,
    textareaRef: outlineTextareaRef
  }
}

// 内容引用配置
const contentRefs = {
  content: chapterContent,
  outline: chapterOutline
}

// 加载文本配置
const loadingTexts = {
  content: '正在生成章节正文',
  outline: '正在生成章节细纲'
}

// 生成配置
const generateConfig = {
  content: {
    title: '生成章节正文',
    confirmText: '开始生成',
    templateCategory: '正文',
    modalClass: 'generate-content-dialog',
    loadingType: 'content',
    validateContent: () => {
      if (!chapterOutline.value.trim()) {
        message.warning('请先输入章节细纲')
        return false
      }
      return true
    },
    getUserPrompt: () => {
      return chapterOutline.value.trim()
    },
    errorMessage: '生成章节正文失败',
    successMessage: '章节正文生成成功'
  },
  outline: {
    title: '生成章节细纲',
    confirmText: '开始生成',
    templateCategory: '细纲',
    modalClass: 'generate-outline-dialog',
    loadingType: 'outline',
    validateContent: () => {
      // 细纲生成不需要验证内容
      return true
    },
    getUserPrompt: () => {
      // 可以根据需要构建细纲生成的提示词
      return `请为章节生成细纲，章节标题：${selectedChapter.value?.title || ''}`
    },
    errorMessage: '生成章节细纲失败',
    successMessage: '章节细纲生成成功'
  }
}

// 计算属性已删除，因为章节在打开页面前就应该存在

// 加载章节数据
const loadChapterData = async () => {
  const bookId = Number(route.params.id)
  // 修改：使用chapterNumber而不是chapterId来匹配路由参数
  const chapterNumber = Number(route.params.chapterNumber)
  
  if (!bookId || !chapterNumber) {
    message.error('无效的书籍或章节号')
    return
  }
  
  loading.value = true
  
  try {
    // 使用chapterNumber获取章节数据
    const response = await chapterContentApi.getChapterByBookIdAndNumber(bookId, chapterNumber)
    if (response.code === 0 && response.data) {
      selectedChapter.value = response.data
      chapterContent.value = response.data.content || ''
      chapterOutline.value = response.data.chapterOutline || ''
    } else {
      message.error('获取章节数据失败')
    }
  } catch (error) {
    console.error('获取章节数据失败:', error)
    message.error('获取章节数据失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadChapterData()
})

// 监听路由参数变化
watch(() => route.params, (newParams) => {
  const bookId = Number(newParams.id)
  // 修改：使用chapterNumber而不是chapterId来匹配路由参数
  const chapterNumber = Number(newParams.chapterNumber)
  
  if (bookId && chapterNumber) {
    loadChapterData()
  }
}, { immediate: true })

// 重置章节
const resetChapter = () => {
  if (!selectedChapter.value) {
    message.warning('没有可重置的章节')
    return
  }

  dialog.warning({
    title: '确认重置',
    content: '确定要重置当前章节吗？此操作将撤销所有未保存的修改，并从服务器重新加载原始数据。',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      loadChapterData()
      message.success('章节已重置')
    }
  })
}

// 切换预览模式
const togglePreviewMode = () => {
  isPreviewMode.value = !isPreviewMode.value
}

// 复制内容
const copyContent = (tab) => {
  const content = contentRefs[tab].value
  
  if (!content.trim()) {
    message.warning('当前内容为空，无法复制')
    return
  }
  
  // 使用现代浏览器的Clipboard API
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(content).then(() => {
      message.success('内容已复制到剪贴板')
    }).catch(err => {
      console.error('复制失败:', err)
      message.error('复制失败，请稍后重试')
    })
  } else {
    // 降级方案：使用传统方法
    const textarea = document.createElement('textarea')
    textarea.value = content
    textarea.style.position = 'fixed'
    textarea.style.left = '-999999px'
    textarea.style.top = '-999999px'
    document.body.appendChild(textarea)
    textarea.focus()
    textarea.select()
    
    try {
      document.execCommand('copy')
      message.success('内容已复制到剪贴板')
    } catch (err) {
      console.error('复制失败:', err)
      message.error('复制失败，请稍后重试')
    } finally {
      document.body.removeChild(textarea)
    }
  }
}

// 清空内容
const clearContent = (tab) => {
  contentRefs[tab].value = ''
  message.success('内容已清空')
}

// 显示生成对话框
const showGenerateContentDialog = () => {
  currentGenerateType.value = 'content'
  const config = generateConfig.content
  
  generateDialogTitle.value = config.title
  generateDialogConfirmText.value = config.confirmText
  generateDialogTemplateCategory.value = config.templateCategory
  generateDialogModalClass.value = config.modalClass
  
  // 重置表单
  generateDialogForm.value = {
    modelId: null,
    systemPromptId: null,
    appendMode: 'overwrite'
  }
  
  generateDialogVisible.value = true
}

// 显示生成细纲对话框
const showGenerateOutlineDialog = () => {
  currentGenerateType.value = 'outline'
  const config = generateConfig.outline
  
  generateDialogTitle.value = config.title
  generateDialogConfirmText.value = config.confirmText
  generateDialogTemplateCategory.value = config.templateCategory
  generateDialogModalClass.value = config.modalClass
  
  // 重置表单
  generateDialogForm.value = {
    modelId: null,
    systemPromptId: null,
    appendMode: 'overwrite'
  }
  
  generateDialogVisible.value = true
}

// 生成对话框事件处理
const handleGenerateModelSelect = (modelId) => {
  generateDialogForm.value.modelId = modelId
}

const handleGenerateTemplateSelect = (templateId) => {
  generateDialogForm.value.systemPromptTemplateId = templateId
}

const handleGenerateCancel = () => {
  generateDialogVisible.value = false
}

// 统一的内容生成函数
const generateContent = async (type) => {
  const config = generateConfig[type]
  
  if (!selectedChapter.value) {
    message.info('请先创建章节')
    return
  }
  
  // 验证表单
  if (!generateDialogForm.value.modelId) {
    message.error('请选择模型')
    return
  }
  
  // 验证内容
  if (!config.validateContent()) {
    return
  }
  
  // 获取用户提示词
  const userPrompt = config.getUserPrompt()
  if (!userPrompt) {
    return
  }
  
  generateDialogLoading.value = true
  generateDialogVisible.value = false
  
  // 启动加载动画
  startLoadingAnimation(config.loadingType)
  
  try {
    // 获取textarea元素的引用
    const refs = elementRefs[type]
    if (refs?.editorRef?.value) {
      refs.textareaRef.value = refs.editorRef.value
    }
    
    // 获取内容引用
    const contentRef = contentRefs[type]
    
    // 保存原始内容，以防接口调用失败
    const originalContent = contentRef.value
    
    // 构建请求参数
    const request = {
      modelId: generateDialogForm.value.modelId,
      systemPromptId: generateDialogForm.value.systemPromptId,
      userPrompt: userPrompt,
      bookId: selectedChapter.value.bookId,
      business: config.title
    }
    
    // 调用通用流式生成接口
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080'}/common/stream/generate`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/plain;charset=UTF-8'
      },
      body: JSON.stringify(request)
    })
    
    if (!response.ok) {
      // 恢复原始内容
      contentRef.value = originalContent
      throw new Error(config.errorMessage)
    }
    
    // 根据生成方式决定是否清空当前内容
    if (generateDialogForm.value.appendMode === 'overwrite') {
      contentRef.value = ''
      // 覆盖生成时，将光标定位到开头
      setCursorToStart(config.loadingType)
    } else {
      // 追加生成时，将光标定位到结尾
      setCursorToEnd(config.loadingType)
    }
    
    // 在开始接收流式数据前停止加载动画，让用户看到打字机效果
    stopLoadingAnimation()
    
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''
    
    // 处理流式数据
    while (true) {
      const { done, value } = await reader.read()
      
      if (done) {
        // 流结束时停止加载动画
        stopLoadingAnimation()
        break
      }
      
      // 后端返回的是纯文本流，不是JSON格式
      const chunk = decoder.decode(value, { stream: true })
      
      // 直接将文本块添加到内容中
      if (chunk) {
        contentRef.value += chunk
        // 使用nextTick确保DOM更新，实现打字机效果
        nextTick(() => {
          scrollToBottom(config.loadingType)
        })
      }
    }
    
    stopLoadingAnimation()
    message.success(config.successMessage)
  } catch (error) {
    console.error(config.errorMessage + ':', error)
    stopLoadingAnimation()
    message.error(config.errorMessage + '，请稍后重试')
  } finally {
    generateDialogLoading.value = false
  }
}

// 确认生成
const handleGenerateConfirm = () => {
  generateContent(currentGenerateType.value)
}

// 光标定位函数
const setCursorToStart = (type) => {
  const refs = elementRefs[type]
  if (refs?.textareaRef?.value) {
    refs.textareaRef.value.setSelectionRange(0, 0)
    refs.textareaRef.value.focus()
  }
}

const setCursorToEnd = (type) => {
  const refs = elementRefs[type]
  if (refs?.textareaRef?.value) {
    const length = refs.textareaRef.value.value.length
    refs.textareaRef.value.setSelectionRange(length, length)
    refs.textareaRef.value.focus()
  }
}

// 滚动到底部
const scrollToBottom = (type) => {
  const refs = elementRefs[type]
  if (refs?.textareaRef?.value) {
    refs.textareaRef.value.scrollTop = refs.textareaRef.value.scrollHeight
  }
}

// 启动加载动画
const startLoadingAnimation = (type) => {
  const refs = elementRefs[type]
  if (refs?.editorRef?.value) {
    refs.textareaRef.value = refs.editorRef.value
  }
  
  // 设置加载状态
  if (type === 'content') {
    contentLoading.value = true
  } else if (type === 'outline') {
    outlineLoading.value = true
  }
}

// 停止加载动画
const stopLoadingAnimation = () => {
  contentLoading.value = false
  outlineLoading.value = false
}

// 创建章节方法已删除，因为章节在打开页面前就应该存在

// 保存章节
const saveChapter = async () => {
  if (!selectedChapter.value) {
    message.info('请先创建章节')
    return
  }
  
  saving.value = true
  
  try {
    // 准备保存数据
    const chapterData = {
      id: selectedChapter.value.id,
      bookId: selectedChapter.value.bookId,
      chapterNumber: selectedChapter.value.chapterNumber,
      chapterTitle: selectedChapter.value.title || '',
      chapterOutline: chapterOutline.value,
      content: chapterContent.value,
      wordNum: chapterContent.value.length,
      version: selectedChapter.value.version
    }
    
    // 调用API保存章节
    const response = await chapterContentApi.saveOrUpdateChapter(chapterData)
    
    if (response.code === 0) {
      // 更新本地章节数据
      selectedChapter.value = {
        ...selectedChapter.value,
        content: chapterContent.value,
        chapterOutline: chapterOutline.value
      }
      
      message.success('章节保存成功')
    } else {
      message.error(`章节保存失败: ${response.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('保存章节出错:', error)
    message.error('保存章节时发生错误')
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
@import '../styles/ChapterPreviewRefactored.css';
</style>